package concurrent.demo1;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * 测试CompletionService实现多任务结果汇总
 *
 * @Author: zhenzhong.wang@honeywell.com
 * @Date: 2018/12/18 7:49 PM
 */
public class CompletionServiceTest {

  private final ExecutorService executor = Executors.newFixedThreadPool(10);

  @Test
  public void main() throws InterruptedException, ExecutionException {
    CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);
    for (int i = 1; i <= 3; i++) {
      int a = 100 * i;
      completionService.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
          System.out.println("print first");
          return a * 10;
        }
      });
    }

    Integer sum = 0;
    for (int i = 0; i < 3; i++) {
      Future<Integer> future = completionService.take();
      sum += future.get();
    }
    System.out.println(sum);
  }

}
